<?php

//$pagestartime=microtime();//记录执行开始时间

/**
 * Created by allen.qiang.
 * 订单抽奖活动AJAX类
 * Date: 15-3-27
 * @author allen.qiang@fistforward.com
 * MK-FUN-AC-0018
 */
quanli_require('module/func/eai.func.php');
quanli_require('module/base/activity/activityConfig.class.php');//活动配置文件
quanli_include('module/base/promotion/quanliCoupon.class.php');//加载优惠券类

class ajax_luck{

    //奖品配置
    private $prize_arr = array(
        '0' => array('id'=>1,'name'=>'大白玩偶','n'=>8,
            'city'=>array(
                '110'=>6,
                '641'=>1,
                '665'=>1
            )
        ),
        '1' => array('id'=>2,'name'=>'大白U型枕','n'=>30,
            'city'=>array(
                '110'=>26,
                '641'=>3,
                '665'=>1
            )
        ),
        '2' => array('id'=>3,'name'=>'8元红包','couponID'=>931,'n'=>13),
        '3' => array('id'=>4,'name'=>'5元红包','couponID'=>930,'n'=>26),
        '4' => array('id'=>5,'name'=>'100积分','n'=>123)
    );

    private $pcustID;//会员号:int
    private $custID;//会员名/手机号:int

    private $start_time;//活动开始时间:datetime
    private $end_time;//活动技术时间:datetime
    private $activityNumber;//活动编号:string
    private $activityPromotion;//活动促销渠道编号:int

    private $bill_no;//订单号:string
    private $bill_code;//订单编号:string
    private $bill_type;//订单类型:decimal
    private $billPromotion;//订单促销渠道编号:int
    private $bill_card_money;//代金卡抵扣金额:decimal
    private $pay_status;//付款状态:0未付款;1全付;2部分付
    private $pay_type;//主支付方式类型：1、货到付款 2、在线支付
    private $deliver_cityid;//配送城市上海110，杭州641，苏州665
    private $send_date;//配送日期

    private $pid;//中奖id:int

    private $debug = false;//开启调试

    public function __construct(){

        global $G_SHOP;

        //实例化配置类
        $activity_config = new activityConfig('LO2015');

        $config_array =  $activity_config->config;

        if($config_array){
            $this->start_time = $config_array['start_time'];
            $this->end_time = $config_array['end_time'];
            $this->activityNumber = $config_array['activityNumber'];
            $this->activityPromotion = $config_array['billPromotion'];
            if(isset($config_array['debug']) && $_REQUEST['debug']=='true'){
                $this->debug = true;
            }

            $new_prize_arrr = $this->prize_arr;
            $new_prize_arrr[4]['n'] = $config_array['chance'];

            $this->prize_arr = $new_prize_arrr;
        }

        $this->pcustID =  $G_SHOP->currentPCustID;//用户ID
        $this->custID =  $G_SHOP->currentCustomerID;//手机号

        unset($G_SHOP,$activity_config,$config_array);

    }

    //抽奖流程逻辑
    public function execute() {

        if(date('Y-m-d H:i:s') > $this->start_time && date('Y-m-d H:i:s') < $this->end_time){

            if(!$this->pcustID){//判断登陆
                $return['login'] = 0;
                $return['msg'] = '亲，请先登陆/注册</br>才能抽奖赢大白哦~';
                $return['alert'] = 0;
            }else{
                $return['login'] = 1;

                if(!$this->check_user_buy()){//判断购买
                    $return['status'] = 0;
                    $return['msg'] = '亲，购买蛋糕</br>才能抽奖赢大白哦~';
                    $return['action'] = '<a href="/" target="_blank" class="confirm">去购买</a>';
                    $return['alert'] = 1;
                }else{

                    if($this->pay_status==0 && $this->pay_type==2){//等于0表示未付款，测试时设置成不等于0
                        $return['status'] = 0;
                        $return['msg'] = '亲，订单付款后</br>才能抽奖赢大白哦~';
                        $return['action'] = '<a href="/shop/payment.html?bill_no='.$this->bill_no.'" target="_blank" class="confirm">去付款</a>';
                        $return['alert'] = 2;
                        $return['href'] = '/shop/payment.html?bill_no='.$this->bill_no;
                    }else{
                        if($this->check_user_log()){//判断今天是否参加过抽奖
                            $return['status'] = 0;
                            $return['msg'] = '您已经抽过奖啦，</br>请明天再来~';
                            $return['alert'] = 3;
                        }else{
                            $bill_status = $this->bill_status;

                            if($bill_status >= 5){

                                $return['status'] = 0;

                                switch ($bill_status)
                                {
                                    case 5://配送
                                        $msg = "在配送中";
                                        $return['alert'] = 4;
                                        break;
                                    case 6://配送
                                        $msg = "在配送中";
                                        $return['alert'] = 4;
                                        break;
                                    case 7://完成
                                        $msg = "完成";
                                        $return['alert'] = 5;
                                        break;
                                    case 10://取消
                                        $msg = "取消";
                                        $return['alert'] = 5;
                                        break;
                                }

                                $return['msg'] = "您的订单已{$msg}，</br>不能参加抽奖活动~";

                            }else{
                                if(!$this->check_order_rule()){//检查订单是否和参加抽奖
                                    $return['status'] = 0;
                                    $return['msg'] = '您不符合本活动抽奖资格，</br>具体详情请查看活动规则。';
                                    $return['alert'] = 5;
                                }else{//参加抽奖流程

                                    $return['status'] = 1;

                                    $prize_arr = $this->prize_arr;

                                    //时间节点:2015年4月28日23:00开始，抽奖奖品一律为100积分直到2015年4月29日10:00活动下线
                                    if(time() >= strtotime('2015-04-28 23:00:00') || date('Y-m-d') == $this->send_date){
                                        $myPid = 5;
                                        $return['pid'] = 5;
                                        $return['msg'] = '恭喜您，</br>抽中100积分~';
                                    }else{

                                        $arr = array();

                                        foreach ($prize_arr as $key => $val) {
                                            $arr[$val['id']] = $val['n'];
                                        }

                                        $pid = $this->get_rand_prize($arr); //根据概率获取奖品id:[1-5]

                                        $rid = $pid-1;//奖品数组id:[0-4]

                                        $res = $prize_arr[$rid]; //奖品信息

                                        if($res['id']==5){ //100积分

                                            $myPid = $pid;
                                            $return['pid'] = $pid;
                                            $return['msg'] = '恭喜您，</br>抽中100积分~';
                                        }else{//如果不是100积分需要判断奖品库存,有返回true，没有返回false

                                            if($this->check_prize_stock($pid)){

                                                $myPid = $pid;
                                                $return['pid'] = $pid;

                                                switch($pid){
                                                    case 1;
                                                        $return['msg'] = '恭喜您，</br>抽中大白玩偶~';
                                                        break;
                                                    case 2;
                                                        $return['msg'] = '恭喜您，</br>大白U型枕~';
                                                        break;
                                                    case 3;
                                                        $return['msg'] = '恭喜您，</br>抽中8元红包，红包已打入</br>【我的优惠券】';
                                                        break;
                                                    case 4;
                                                        $return['msg'] = '恭喜您，</br>抽中5元红包，红包已打入</br>【我的优惠券】';
                                                        break;
                                                }

                                            }else{//没库存直接送100积分

                                                $myPid = 5;
                                                $return['pid'] = 5;
                                                $return['msg'] = '恭喜您，</br>抽中100积分~';
                                            }
                                        }
                                    }

                                    $this->pid = $myPid;

                                    if(!$this->create_luck_order()){//数据库操作部分
                                        unset($return['pid']);
                                        $return['status'] = 0;
                                        $return['msg'] = '抽奖的队伍太大了，</br>亲先排好队，稍后再试哦~';
                                        $return['alert'] = 6;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            echo json_encode($return);
        }
    }

    //查询用户订单，数据初始化
    function check_user_buy(){

        global $G_SHOP;

        //$start_time = date('Y-m-d').' 00:00:00';
        $start_time = $this->start_time;
        $end_time = date('Y-m-d').' 23:59:59';

        //查询抽奖记录bill_no
        $log_sql = "select extend_8 from activities_extend where activityNumber = 'LO2015' and creator = '{$G_SHOP->currentCustomerID}' and extend_8 != null";

        $logs = $G_SHOP->DBCA->stmt_query($log_sql);

        $sql = "select bill_no,bill_code,bill_status,pay_status,pay_type,billPromotion,bill_card_money,deliver_cityid,send_date from bill_master where pcustID = ".$this->pcustID." and bill_status < 10 and createTime between '{$start_time}' and '{$end_time}'";

        if($logs){

            $bill_no = '';

            foreach($logs as $k => $val){
                $bill_no .= $k==0 ? $val : ','.$val;
            }

            $sql .= " and bill_no not in({$bill_no})";
        };

        $sql .= " order by createTime asc limit 1";

        $result =  $G_SHOP->DBCA->stmt_query($sql);

        if($result){

            $this->bill_no = $result[0]->bill_no;//订单号
            $this->bill_code = $result[0]->bill_code;//订单编号
            $this->bill_status = $result[0]->bill_status;//订单状态
            $this->pay_status = $result[0]->pay_status;//付款状态
            $this->pay_type = $result[0]->pay_type;//付款状态
            $this->billPromotion = $result[0]->billPromotion;//订单促销渠道
            $this->bill_card_money = $result[0]->bill_card_money;//代金卡抵扣金额
            $this->deliver_cityid = $result[0]->deliver_cityid;//配送城市ID
            $this->send_date = $result[0]->send_date;//配送日期

            return true;

        }else{

            return false;

        }

        unset($G_SHOP,$sql,$result);
    }

    /* * * * * * * * * * * * * * * * *
     * 排除渠道
     *  第一类：
     * “屈臣氏拿破仑mini订购 ID:486”
     *  第二类：
     * “LV5会员5折 ID:373”
     *  第三类：
     * “农行信用卡5折 ID:374”
     * “浦发银行5折购 ID:445”
     * “杭州农行5折购 ID:460”
     *  第四类
     * “敢聊商城 ID:485”
     * “生活杉德 ID:432”
     * “中智订单 ID:280”
     * “生日管家订单 ID:281”
     * “甜派订单(蛋定) ID:282”
     * “百联E城 ID:230”
     * * * * * * * * * * * * * * * * */

    //检查订单是否符合抽奖条件
    function check_order_rule(){

        $rule = 0;

        $ids = array(486,373,374,445,460,485,432,280,281,282,230);

        $id = $this->billPromotion;

        if(in_array($id,$ids)){
            ++$rule;
        }

        //订单类型；1、正常订单 2、生日会蛋糕 3、市场推广 4、其他订单 5、补偿订单 6、测试订单 7、招待赠送 8、大客户订单 9、试吃订单
        $types = array(2,3,7);

        $type = $this->bill_type;

        if(in_array($type,$types)){
            ++$rule;
        }

        if($this->bill_card_money>0){//使用代金卡、现金卡抵扣额度
            ++$rule;
        }

        return $rule==0 ? true : false;

        unset($rule,$ids,$id,$types,$type);
    }

    //检查用户是否抽奖
    function check_user_log(){

        global $G_SHOP;

        $start_time = date('Y-m-d').' 00:00:00';
        $end_time = date('Y-m-d').' 23:59:59';

        $sql = "select uuid from activity_log where creator={$this->pcustID} and sku='{$this->activityNumber}' and createTime between '{$start_time}' and '{$end_time}'";

        $result = $G_SHOP->DBCA->stmt_query($sql) ? true : false;

        return $result;

        unset($G_SHOP,$start_time,$end_time,$sql,$result);
    }

    //生成uuid
    function get_uuid($type='log'){

        $uuid = $this->activityPromotion.date('Ymd').$this->pcustID.$type;//促销渠道+日期+用户ID

        return md5($uuid);

        unset($uuid);
    }

    //检查奖品库存
    function check_prize_stock($pid){

        global $G_SHOP;

        $rid = $pid-1;

        $prize_array = $this->prize_arr;

        $current_prize = $prize_array[$rid];//当前抽中奖品信息

        $start_time = date('Y-m-d',time()).' 00:00:00';
        $end_time = date('Y-m-d H:i:s',time());

        //extend_1 城市，extend_4 奖品ID，extend_5 奖品名称，extend_6 促销渠道

        $sql = "select count(uuid) as num from activities_extend
                where activityNumber='{$this->activityNumber}' and classifyID='log'
                and createTime between '{$start_time}' and '{$end_time}'";

        if(in_array($pid,array('3','4'))){//如果是红包不判断所在城市

            $sql .= " and extend_4={$pid}";

            $prize_num = $current_prize['n'];//奖品数量
        }else{//实物奖励

            $sql .= " and extend_1={$this->deliver_cityid} and extend_4={$pid}";

            $prize_num = $current_prize['city'][$this->deliver_cityid];//奖品数量
        }

        $result = $G_SHOP->DBCA->stmt_query($sql);

        $log_num = $result[0]->num;

        //echo $sql,'</br>';
        //echo '已出现【',$current_prize['name'],'】数量：',$log_num,'，规定每天出现数量：',$prize_num,'</br>';

        if($log_num < $prize_num){
            return true;
        }else{
            return false;
        }

        unset ($G_SHOP, $arr_id, $prize_array, $current_prize, $prize_num, $start_time, $end_time, $sql, $result, $log_num);
    }

    //中奖概率算法
    function get_rand_prize($proArr) {

        $result = '';

        //概率数组的总概率精度
        $proSum = array_sum($proArr);

        //概率数组循环
        foreach ($proArr as $key => $proCur) {
            $randNum = mt_rand(1, $proSum);
            if ($randNum <= $proCur) {
                $result = $key;
                break;
            } else {
                $proSum -= $proCur;
            }
        }

        return $result;

        unset($result,$proSum,$proArr);
    }

    //数据操作，更新bill_master,发放优惠券/红包，添加抽奖记录，添加报表记录
    private function create_luck_order(){

        if(!empty($this->pid)){

            global $G_SHOP;

            $pid = $this->pid;//奖品ID
            $rid = $pid-1;//奖品数组ID
            $remark = $this->prize_arr[$rid]['name'];//奖品名称

            try {

                //事务开始
                $G_SHOP->DBCA->beginTransaction();

                if(!$this->debug){

                    //添加用户参加活动记录activity_log
                    $activity_log = new entity('activity_log');
                    $activity_log->timeStamp = date('Y-m-d H:i:s');
                    $activity_log->creator = $this->pcustID;
                    $activity_log->createTime = date('Y-m-d H:i:s');
                    $activity_log->pcustID = $this->pcustID;
                    $activity_log->sku = $this->activityNumber;

                    $G_SHOP->DBCA->save($activity_log);

                }

                //记录参加活动的扩展信息activities_extend
                $activities_extend_log = new entity('activities_extend');
                $activities_extend_log->timeStamp = date('Y-m-d H:i:s');
                $activities_extend_log->creator = $this->custID;
                $activities_extend_log->activityNumber = $this->activityNumber;
                $activities_extend_log->classifyID = 'log';
                $activities_extend_log->extend_1 = $this->deliver_cityid;
                $activities_extend_log->extend_4 = $this->pid;
                $activities_extend_log->extend_5 = $remark;
                $activities_extend_log->extend_6 = $this->activityPromotion;
                $activities_extend_log->extend_8 = $this->bill_no;

                $G_SHOP->DBCA->save($activities_extend_log);

                if(in_array($pid,array(1,2))){//如果是实物奖品
                    //更新bill_master
                    $update_bill_master = "update bill_master set remark=? where bill_no=?";
                    $G_SHOP->DBCA->stmt_query($update_bill_master,'ss',$remark,$this->bill_no);
                }else{
                    switch($pid){
                        case 3://8元红包
                            $this->give_coupon_to_user($pid);
                            break;
                        case 4://5元红包
                            $this->give_coupon_to_user($pid);
                            break;
                        default://100积分
                            $this->give_points_to_user($pid);
                            break;
                    }
                }

                //事务结束
                $G_SHOP->DBCA->commit();

                return true;

            } catch (Exception $e) {

                //事务回滚
                $G_SHOP->DBCA->rollBack();

                if ($e->getCode() > 0) {
                    return false;

                } else {
                    error_log($e->getMessage());
                    return false;
                }
            }

            unset($G_SHOP,$pid,$rid,$activity_log,$activities_extend_log,$update_bill_master);
        }else{
            return false;
        }
    }

    //发送红包/优惠券
    private function give_coupon_to_user($pid){

        --$pid;//奖品数字ID

        //实例优惠券类
        $ebsigCoupon = new quanliCoupon();

        $prize = $this->prize_arr[$pid];

        $couponID = $prize['couponID'];

        //发送优惠券
        $ebsigCoupon->createCouponCode($couponID,array($this->custID),false);

        unset($pid,$ebsigCoupon,$prize,$couponID);
    }

    //发送积分
    private function give_points_to_user(){

        global $G_SHOP;

        //实例crm类
        $crm_obj = eai_crm();

        //积分日志记录
        $integral_log = new entity('integral_log');
        $integral_log->creator = $this->custID;
        $integral_log->pcustID = $this->pcustID;
        $integral_log->logType = 3;//大白抽奖积分日志类型
        $integral_log->logName = "订单：{$this->bill_code}，参加抽奖，积分+100";
        $integral_log->logValue='100';

        $G_SHOP->DBCA->save($integral_log);//大白抽奖日志表

        //积分账户充值
        $arg_array = array(
            'pcustID' => $this->pcustID,
            'subjectId' => G_POINTS_ID,
            'amount' => 100,
            'operator' => 'system',
            'remark' => "订单：{$this->bill_code}，参加抽奖，积分+100"
        );

        $crm_obj->recharge($arg_array,false);
    }

    //保存数据/销毁变量
    public function __destruct(){

    }

}

//$pageendtime = microtime();
//$starttime = explode(" ",$pagestartime);
//$endtime = explode(" ",$pageendtime);
//$totaltime = $endtime[0]-$starttime[0]+$endtime[1]-$starttime[1];
//$timecost = sprintf("%s",$totaltime);
//echo "页面运行时间: $timecost 秒</br>";